<!-- ApprovalFlow.vue -->
<template>
  <VueFlow
      :nodes="nodes"
      :edges="edges"
      fit-view
      class="w-full h-[600px] border rounded"
  >
    <Background />
    <Controls />
  </VueFlow>
</template>

<script setup>
import { ref, watch } from 'vue'
import { VueFlow, Background, Controls, useVueFlow } from '@braks/vue-flow'
import '@braks/vue-flow/dist/style.css'

// 接收 props
const props = defineProps({
  processList: {
    type: Array,
    required: true
  }
})

const { addNodes, addEdges } = useVueFlow()
const nodes = ref([])
const edges = ref([])

// 监听 props 变化，生成节点和边
watch(
    () => props.processList,
    (list) => {
      const newNodes = []
      const newEdges = []

      const getColorByStatus = (status) => {
        switch (status) {
          case '同意':
            return '#67C23A'
          case '驳回':
            return '#F56C6C'
          case '审批中':
            return '#409EFF'
          default:
            return '#909399'
        }
      }

      list.forEach((node, index) => {
        const nodeId = `node-${index}`
        const handlers = node.handlers
            .map(h => `👤 ${h.userid}（${h.status}）`)
            .join('\n')
        const label = `${node.nodeType}（${node.approvalType}）\n${handlers}`

        newNodes.push({
          id: nodeId,
          label,
          type: 'default', // ✅ 必须指定
          position: { x: 100 + index * 280, y: 200 },
          style: {
            backgroundColor: node.current ? '#ecf5ff' : '#ffffff',
            border: `2px solid ${getColorByStatus(node.status)}`,
            borderRadius: '12px',
            padding: '10px',
            whiteSpace: 'pre-line',
            fontSize: '14px',
            color: '#333'
          }
        })

        if (index > 0) {
          newEdges.push({
            id: `e-${index - 1}-${index}`,
            source: `node-${index - 1}`,
            target: nodeId,
            label: node.status,
            style: {
              stroke: getColorByStatus(node.status)
            },
            animated: node.current,
          })
        }
      })

      nodes.value = newNodes
      edges.value = newEdges
    },
    { immediate: true }
)
</script>

<style scoped>
/* 可选：增加全局字体 */
.vue-flow__node {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
::v-deep(.vue-flow__edge-textbg) {
  fill: white;
  fill-opacity: 1;
}
</style>
